<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-03 00:33:05
 * @LastEditTime: 2023-10-03 14:31:15
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Models;

use App\Traits\MaterialTrait;
use App\Traits\SoftDeletesTrait;

class FinanceVoucherDetails extends BaseModel
    {
    use MaterialTrait;
    use SoftDeletesTrait;
    public $timestamps = true;
    public $table = "sys_finance_voucher_details";
    protected $guarded = [];
    protected $casts = [];

    public function company()
        {
        return $this->belongsTo(Company::class);
        }
    public function main()
        {
        return $this->belongsTo(FinanceVoucher::class, "main_id");
        }
    public function trade()
        {
        return $this->belongsTo(Trade::class);
        }
    public function status()
        {
        return $this->belongsTo(Dic::class, "status_id", "key")->where(function ($q)
            {
            $q->where("code", 'Finance_Status');
            });
        }

    public function department()
        {
        return $this->belongsTo(FinanceDepartment::class);
        }

    public function subject()
        {
        return $this->belongsTo(Subject::class);
        }
    //设置客户余额
    public function _created($model)
        {
        if (in_array($model->subject_id, ['1122', '2202']))
            $model->company->updateFinanceBalance($model->amount, $model->debit_amount, $model->credit_amount, $model->debit_invoice_amount, $model->credit_invoice_amount);
        }

    //设置客户余额
    public function _deleted($model)
        {
        if (in_array($model->subject_id, ['1122', '2202']))
            $model->company->updateFinanceBalance(0 - $model->amount, 0 - $model->debit_amount, 0 - $model->credit_amount, 0 - $model->debit_invoice_amount, 0 - $model->credit_invoice_amount);
        $model->status_id = -1;
        $model->save();
        }
    //恢复删除
    public function _restored($model)
        {
        if (in_array($model->subject_id, ['1122', '2202']))
            $model->company->updateFinanceBalance($model->amount, $model->debit_amount, $model->credit_amount, $model->debit_invoice_amount, $model->credit_invoice_amount);
        }
    }
